{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-12-02T08:40:54.114095Z",
     "start_time": "2024-12-02T08:40:45.813663Z"
    }
   },
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from torchvision import datasets, transforms\n",
    "from torch.utils.data import DataLoader\n",
    "\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T08:40:55.042808Z",
     "start_time": "2024-12-02T08:40:55.023224Z"
    }
   },
   "cell_type": "code",
   "source": [
    "data_dir=\"C:/Users/Lenovo/Desktop/深度/实验三数据集/车辆分类数据集\"\n",
    "transform = transforms.Compose([\n",
    "    transforms.Resize((128, 128)),\n",
    "    transforms.ToTensor(),\n",
    "])\n",
    "\n",
    "dataset = datasets.ImageFolder(data_dir, transform=transform)\n",
    "\n",
    "dataloader = DataLoader(dataset, batch_size=32, shuffle=True,num_workers=4)\n"
   ],
   "id": "ebd9ea0cdc733ce2",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T07:05:34.698456Z",
     "start_time": "2024-12-02T07:05:07.675625Z"
    }
   },
   "cell_type": "code",
   "source": [
    "for images, labels in dataloader:\n",
    "    #print(images.shape)\n",
    "    print(labels)\n",
    "    break"
   ],
   "id": "a4523db2a0ef2896",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([1, 0, 1, 2, 1, 2, 0, 1, 1, 1, 2, 2, 2, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1,\n",
      "        0, 1, 0, 0, 0, 1, 2, 1])\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T08:51:13.434042Z",
     "start_time": "2024-12-02T08:51:13.420080Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def convMul(x, y):\n",
    "    batch, hight, wide = x.shape\n",
    "    y_h, y_w = y.shape\n",
    "    result= torch.zeros(batch, hight-y_h+1, wide-y_w+1).to(device)\n",
    "    for i in range(result.shape[1]):\n",
    "        for j in range(result.shape[2]):\n",
    "            result[:, i, j]=(x[:,i:i+y_h,j:j+y_w] * y).sum(dim=2).sum(dim=1)\n",
    "    return result\n",
    "\n",
    "def cor_Multi_in(x, y):\n",
    "    result=convMul(x[:,0,:,:], y[0,:,:])\n",
    "    for i in range(x.shape[1]):\n",
    "        result+=convMul(x[:,i,:,:], y[i,:,:])\n",
    "    \n",
    "    return result\n",
    "\n",
    "def cor_Multi_out(x, Y):\n",
    "    return torch.stack([cor_Multi_in(x, y)for y in Y], dim=1)\n",
    "        "
   ],
   "id": "75e5488531cf3569",
   "outputs": [],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T08:51:21.805797Z",
     "start_time": "2024-12-02T08:51:21.791645Z"
    }
   },
   "cell_type": "code",
   "source": [
    "class Myconv2D(nn.Module):\n",
    "    def __init__(self,in_channels, out_channels, kernel_size):\n",
    "        super(Myconv2D, self).__init__()\n",
    "        kernel_size=(kernel_size, kernel_size)\n",
    "        self.weight = nn.Parameter(torch.Tensor(in_channels, out_channels, *kernel_size))\n",
    "        self.bias = nn.Parameter(torch.Tensor(out_channels,126,126))\n",
    "        self.reset_parameters()\n",
    "    \n",
    "    def reset_parameters(self):\n",
    "        self.weight.data.normal_(0, 0.01)\n",
    "        self.bias.data.zero_()    \n",
    "        \n",
    "    def forward(self, x):\n",
    "        return cor_Multi_out(x, self.weight) + self.bias\n",
    "        "
   ],
   "id": "53dcf46b42e0943c",
   "execution_count": 14,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T09:05:05.125226Z",
     "start_time": "2024-12-02T09:05:05.115420Z"
    }
   },
   "cell_type": "code",
   "source": [
    "class MyConvNet(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(MyConvNet, self).__init__()\n",
    "        self.layer1 = nn.Sequential(\n",
    "            Myconv2D(3, 32, kernel_size=3),\n",
    "            nn.BatchNorm2d(32),\n",
    "            nn.ReLU(inplace=True),\n",
    "        )\n",
    "        self.fc=nn.Linear(in_features=32, out_features=3)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        x = self.layer1(x)\n",
    "        #print(x.shape)\n",
    "        x= F.avg_pool2d(x, 126)\n",
    "        #print(x.shape)\n",
    "        x= x.squeeze()\n",
    "        #print(x.shape)\n",
    "        x = self.fc(x)\n",
    "        return x\n",
    "    "
   ],
   "id": "6a7d4f32252b38d8",
   "outputs": [],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T08:59:16.005748Z",
     "start_time": "2024-12-02T08:59:15.897061Z"
    }
   },
   "cell_type": "code",
   "source": [
    "net = MyConvNet().to(device)\n",
    "criterion= nn.CrossEntropyLoss()\n",
    "optimizer= torch.optim.Adam(net.parameters(),lr=0.01)"
   ],
   "id": "b288998f85cd45da",
   "outputs": [],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T08:59:16.676482Z",
     "start_time": "2024-12-02T08:59:16.660050Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def train_net(net,dataloader):\n",
    "    net.train()\n",
    "    train_batches=len(dataloader)\n",
    "    \n",
    "    for epoch in range(10):\n",
    "        total_loss=0\n",
    "        correct=0\n",
    "        sample_num=0\n",
    "        for batch_idx, (data, target) in enumerate(dataloader):\n",
    "            data=data.to(device).float()\n",
    "            target=target.to(device).long()\n",
    "            \n",
    "            optimizer.zero_grad()\n",
    "            output=net(data)\n",
    "            loss=criterion(output,target)\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "            \n",
    "            #print(\"Batch %d, Loss: %.4f\"%(batch_idx,loss.item()))\n",
    "            \n",
    "            total_loss+=loss.item()\n",
    "            prediction=torch.argmax(output,1)\n",
    "            correct += (prediction==target).sum().item()\n",
    "            sample_num+=len(prediction)\n",
    "            \n",
    "        \n",
    "        loss=total_loss/train_batches\n",
    "        acc=correct/train_batches\n",
    "        print('Loss: {:.4f} Acc: {:.4f}'.format(loss,acc))\n",
    "    return loss,acc\n",
    "        "
   ],
   "id": "b6f023847c9cedab",
   "outputs": [],
   "execution_count": 21
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T09:04:16.732948Z",
     "start_time": "2024-12-02T08:59:17.625780Z"
    }
   },
   "cell_type": "code",
   "source": "train_net(net,dataloader)",
   "id": "d99af787c83a9325",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loss: 0.8598 Acc: 18.9767\n",
      "Loss: 0.7570 Acc: 22.6512\n",
      "Loss: 0.7345 Acc: 22.3488\n",
      "Loss: 0.6887 Acc: 23.8372\n",
      "Loss: 0.6728 Acc: 24.0000\n",
      "Loss: 0.6434 Acc: 24.3023\n",
      "Loss: 0.6379 Acc: 24.6512\n",
      "Loss: 0.6328 Acc: 25.0000\n",
      "Loss: 0.6268 Acc: 25.0698\n",
      "Loss: 0.6156 Acc: 24.8605\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(0.6155804915483608, 24.86046511627907)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "ac562c7e5f7c73cf"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
